import json

from django_celery_beat.models import PeriodicTask, CrontabSchedule
from task.models import ConnectionTask


class ScheduleService:
    def connection_created(self, connection):
        crontab, _ = CrontabSchedule.objects.get_or_create(
            minute='*/15',
            hour='*',
            day_of_week='*',
            day_of_month='*',
            month_of_year='*',
        )
        periodic_task = PeriodicTask.objects.create(
            crontab=crontab,
            name=f'{connection.partner.name}:互联[{connection.id}]:定时更新互联数据',
            task='datacenter.tasks.cron_pull_connection_data',
            args=json.dumps([connection.id])
        )
        ConnectionTask.objects.create(
            connection=connection,
            periodic_task=periodic_task
        )


schedule_service = ScheduleService()
